package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
)

func main() {
	b, err := os.ReadFile(os.Args[1])
	if err != nil {
		panic(err)
	}

	lines := strings.Split(string(b), "\n")
	fmt.Printf("lines: %v\n", len(lines))

	if !strings.HasPrefix(lines[0], "Listing...") && !strings.HasPrefix(lines[0], "正在列表...") {
		log.Fatalln("file is not a 'apt list' output")
		return
	}

	// xfonts-encodings/now 1:1.0.4-2 all [installed,local]
	type Package struct {
		Name    string
		Version string
		Arch    string
		Status  string
	}

	var packages []Package

	for _, line := range lines {
		if strings.HasPrefix(line, "Listing...") || strings.HasPrefix(line, "正在列表...") || line == "" {
			continue
		}

		pkg := Package{}
		{
			fields := strings.SplitN(line, " ", 4)
			switch len(fields) {
			case 4:
				pkg.Status = fields[3]
				fallthrough
			case 3:
				pkg.Arch = fields[2]
				fallthrough
			case 2:
				pkg.Version = fields[1]
				fallthrough
			case 1:
				pkg.Name = fields[0]
			}
		}

		if strings.Contains(pkg.Name, "/") {
			pkg.Name = strings.Split(pkg.Name, "/")[0]
		}
		fmt.Printf("pkg: %v\n", pkg)
		packages = append(packages, pkg)
	}

	f, err := os.OpenFile(os.Args[1]+".clean", os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalf("Failed to open file: %v", err)
		return
	}
	defer f.Close()

	writer := bufio.NewWriter(f)
	for _, pkg := range packages {
		record := fmt.Sprintln(pkg.Name, pkg.Version)
		if _, err := writer.WriteString(record); err != nil {
			log.Printf("Failed to write record for package %s: %v", pkg.Name, err)
			continue
		}
	}
	writer.Flush()
}
